package com.example.interviewassistant;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class QuestionConfigActivity extends AppCompatActivity {
    public static final String EXTRA_RESUME_TEXT = "resume_text";
    public static final String EXTRA_CONFIG = "config";

    private SeekBar seekBarQuestionCount;
    private TextView tvQuestionCount;
    private Spinner spinnerDifficulty;
    private LinearLayout domainsContainer;
    private Button btnGenerate;

    private String resumeText;
    private QuestionGenerationConfig config;
    private List<CheckBox> domainCheckboxes = new ArrayList<>();

    // 预设的技术领域列表
    public static final String[][] DOMAIN_CATEGORIES = {
            {"研发能力", "Java基础", "Spring框架", "数据库", "Redis", "消息队列", "微服务", "设计模式", "并发编程", "JVM", "算法", "网络编程", "Linux", "前端技术", "DevOps", "人工智能"},
            {"技术管理能力", "技术架构设计", "代码评审", "技术文档", "团队协作", "技术决策", "性能优化", "系统重构", "技术风险管理", "技术债务管理", "技术团队管理"},
            {"项目管理能力", "项目规划", "任务分解", "风险管理", "进度跟踪", "资源调配", "沟通协调", "问题解决", "项目复盘", "敏捷管理", "交付管理"},
            {"需求分析能力", "需求收集", "需求分析", "用户场景分析", "业务建模", "功能规格说明", "用户故事编写", "原型设计", "需求优先级排序", "验收标准制定", "需求跟踪"}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_config);

        // 初始化控件
        seekBarQuestionCount = findViewById(R.id.seekBarQuestionCount);
        tvQuestionCount = findViewById(R.id.tvQuestionCount);
        spinnerDifficulty = findViewById(R.id.spinnerDifficulty);
        domainsContainer = findViewById(R.id.domainsContainer);
        btnGenerate = findViewById(R.id.btnGenerate);

        // 获取传入的简历文本
        resumeText = getIntent().getStringExtra(EXTRA_RESUME_TEXT);
        
        // 初始化配置对象
        config = new QuestionGenerationConfig();

        // 设置问题数量滑块
        setupQuestionCountSeekBar();

        // 设置难度下拉框
        setupDifficultySpinner();

        // 设置技术领域选择框
        setupDomainCheckboxes();

        // 设置"生成问题"按钮点击事件
        btnGenerate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveConfig();
                startInterviewQuestions();
            }
        });
    }

    private void setupQuestionCountSeekBar() {
        seekBarQuestionCount.setMax(20);
        seekBarQuestionCount.setProgress(config.getQuestionCount());
        updateQuestionCountText(config.getQuestionCount());

        seekBarQuestionCount.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int count = Math.max(1, progress);
                updateQuestionCountText(count);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    private void updateQuestionCountText(int count) {
        tvQuestionCount.setText(count + " 个问题");
    }

    private void setupDifficultySpinner() {
        String[] difficultyLevels = {"初级", "中等", "高级", "专家"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_spinner_item, difficultyLevels);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerDifficulty.setAdapter(adapter);

        // 设置默认选择
        int position = Arrays.asList(difficultyLevels).indexOf(config.getDifficultyLevel());
        if (position >= 0) {
            spinnerDifficulty.setSelection(position);
        }
    }

    private void setupDomainCheckboxes() {
        for (String[] category : DOMAIN_CATEGORIES) {
            // 创建一个水平布局来放置分类标题和全选复选框
            LinearLayout categoryHeader = new LinearLayout(this);
            categoryHeader.setOrientation(LinearLayout.HORIZONTAL);
            categoryHeader.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));

            // 添加分类标题
            TextView categoryTitle = new TextView(this);
            categoryTitle.setText(category[0]);
            categoryTitle.setTextSize(16);
            categoryTitle.setPadding(0, 24, 0, 8);
            categoryTitle.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
            
            // 添加权重，让分类标题占据主要空间
            LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(
                    0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
            categoryTitle.setLayoutParams(titleParams);
            categoryHeader.addView(categoryTitle);
            
            // 添加全选复选框
            CheckBox selectAllCheckBox = new CheckBox(this);
            selectAllCheckBox.setText("全选");
            categoryHeader.addView(selectAllCheckBox);
            
            // 将整个标题栏添加到容器
            domainsContainer.addView(categoryHeader);
            
            // 为当前分类创建复选框列表
            final List<CheckBox> categoryCheckboxes = new ArrayList<>();
            
            // 添加该分类下的所有选项
            for (int i = 1; i < category.length; i++) {
                CheckBox checkBox = new CheckBox(this);
                checkBox.setText(category[i]);
                checkBox.setTag(category[i]);
                
                // 如果是已选择的领域，设置为选中状态
                if (config.getSelectedDomains().contains(category[i])) {
                    checkBox.setChecked(true);
                }
                
                domainsContainer.addView(checkBox);
                domainCheckboxes.add(checkBox);
                categoryCheckboxes.add(checkBox);
            }
            
            // 设置全选复选框的点击事件
            final List<CheckBox> finalCategoryCheckboxes = categoryCheckboxes;
            selectAllCheckBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isChecked = ((CheckBox) v).isChecked();
                    for (CheckBox cb : finalCategoryCheckboxes) {
                        cb.setChecked(isChecked);
                    }
                }
            });
            
            // 设置子选项的点击事件，以更新全选复选框状态
            for (CheckBox cb : categoryCheckboxes) {
                cb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        updateSelectAllCheckbox(selectAllCheckBox, finalCategoryCheckboxes);
                    }
                });
            }
            
            // 初始化全选复选框状态
            updateSelectAllCheckbox(selectAllCheckBox, categoryCheckboxes);
        }
    }
    
    /**
     * 更新全选复选框的状态
     * @param selectAllCheckBox 全选复选框
     * @param categoryCheckboxes 该分类下的所有复选框
     */
    private void updateSelectAllCheckbox(CheckBox selectAllCheckBox, List<CheckBox> categoryCheckboxes) {
        boolean allChecked = true;
        boolean anyChecked = false;
        
        for (CheckBox cb : categoryCheckboxes) {
            if (cb.isChecked()) {
                anyChecked = true;
            } else {
                allChecked = false;
            }
        }
        
        // 如果所有复选框都选中，则全选复选框也选中
        // 如果部分复选框选中，全选复选框设为未选中状态
        selectAllCheckBox.setChecked(allChecked);
    }

    private void saveConfig() {
        // 保存问题数量
        config.setQuestionCount(Math.max(1, seekBarQuestionCount.getProgress()));

        // 保存难度级别
        config.setDifficultyLevel(spinnerDifficulty.getSelectedItem().toString());

        // 保存选中的技术领域
        List<String> selectedDomains = new ArrayList<>();
        for (CheckBox checkBox : domainCheckboxes) {
            if (checkBox.isChecked()) {
                String domain = checkBox.getTag().toString();
                selectedDomains.add(domain);
                System.out.println("添加选中的领域: " + domain + " (从Tag获取)");
            }
        }
        config.setSelectedDomains(selectedDomains);
        
        // 打印日志，便于调试
        System.out.println("已选择的技术领域总数: " + selectedDomains.size());
        System.out.println("已选择的技术领域列表: " + selectedDomains);
        
        // 按分类打印选中的领域
        for (int i = 0; i < DOMAIN_CATEGORIES.length; i++) {
            String categoryName = DOMAIN_CATEGORIES[i][0];
            List<String> categoryDomains = new ArrayList<>();
            
            for (String domain : selectedDomains) {
                if (isInCategory(domain, i)) {
                    categoryDomains.add(domain);
                }
            }
            
            if (!categoryDomains.isEmpty()) {
                System.out.println(categoryName + " 分类下选中的领域: " + categoryDomains);
            } else {
                System.out.println(categoryName + " 分类下没有选中任何领域");
            }
        }
    }
    
    /**
     * 检查一个领域是否属于指定的类别
     *
     * @param domain 领域名称
     * @param categoryIndex 类别索引
     * @return 是否属于该类别
     */
    private boolean isInCategory(String domain, int categoryIndex) {
        if (categoryIndex >= 0 && categoryIndex < DOMAIN_CATEGORIES.length) {
            String[] category = DOMAIN_CATEGORIES[categoryIndex];
            for (int i = 1; i < category.length; i++) { // 从1开始，跳过类别名称
                if (category[i].equals(domain)) {
                    return true;
                }
            }
        }
        return false;
    }

    private void startInterviewQuestions() {
        // 创建Intent，并将简历文本和配置传递给面试问题Activity
        Intent intent = new Intent(this, InterviewQuestionsActivity.class);
        intent.putExtra(InterviewQuestionsActivity.EXTRA_RESUME_TEXT, resumeText);
        intent.putExtra(InterviewQuestionsActivity.EXTRA_CONFIG, config);
        startActivity(intent);
        finish(); // 结束当前Activity
    }
} 